from rest_framework import serializers
from goods.models import *


# 商品图片序列化类
class GoodsImageSerializer(serializers.ModelSerializer):

    class Meta:
        model = GoodsImage
        fields = '__all__'


# 商品序列化类
class GoodSerializer(serializers.ModelSerializer):

    images = GoodsImageSerializer(many=True)

    class Meta:
        model = Goods
        fields = '__all__'


# 三级分类序列化
class GoodsCategorySerializer3(serializers.ModelSerializer):

    class Meta:
        model = GoodsCategory
        fields = '__all__'


class GoodsCategorySerializer2(serializers.ModelSerializer):

    sub_cat = GoodsCategorySerializer3(many=True)

    class Meta:
        model = GoodsCategory
        fields = '__all__'


class GoodsCategorySerializer(serializers.ModelSerializer):

    sub_cat = GoodsCategorySerializer2(many=True)

    class Meta:
        model = GoodsCategory
        fields = '__all__'


class HotSearchSeriailzer(serializers.ModelSerializer):
    class Meta:
        model = HotSearch
        fields = ("keywords",)


# 轮播图序列化
class BannerSeriailzer(serializers.ModelSerializer):

    class Meta:
        model = Banner
        fields = '__all__'


# 分类品牌序列化
class BrandSerializer(serializers.ModelSerializer):

    class Meta:
        model = GoodsCategoryBrand
        fields = '__all__'


from django.db.models import Q


# 首页商品分类显示
class IndexCategorySerializer(serializers.ModelSerializer):

    brands = BrandSerializer(many=True)

    # 商品不是直接属于一级分类
    goods = serializers.SerializerMethodField()

    # 关联到二级分类
    sub_cat = GoodsCategorySerializer2(many=True)

    def get_goods(self, obj):
        all_goods = Goods.objects.filter(Q(category_id=obj.id) |
                    Q(category__parent_category_id=obj.id) |
                    Q(category__parent_category__parent_category_id=obj.id))
        # 对查到的对象进行序列化
        goods_serializer = GoodSerializer(all_goods, many=True)
        return goods_serializer

    class Meta:
        model = GoodsCategory
        fields = '__all__'









